package com.base.cn.platform.os.common.filter;

import com.base.cn.platform.os.common.utils.result.ResultUtil;
import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.Part;
import java.io.IOException;
import java.util.Collection;

/**
 * 文件上传过滤器
 * @author s.li
 * @date 2019/05/07
 */
@Component
@WebFilter(urlPatterns = "/*", filterName = "fileUploadFilter")
@Slf4j
public class FileUploadFilter implements Filter {
    private Gson gson = new Gson();
    //文件最大限制，单位M
    private int FILE_MAX = 20;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest)request;
        String contentType = req.getHeader("content-type");
        boolean status = true;
        //如果是文件上传
        if(FILE_MAX > 0 && contentType!=null && contentType.contains("multipart/form-data")){
            Collection<Part> partCollection =  req.getParts();
            for(Part part : partCollection){
                String contentDisposition = part.getHeader("content-disposition");
                //如果有包含有文件名
                if(contentDisposition.contains("filename")){
                    String fileName = part.getSubmittedFileName();
                    //如果不是APK
                    if(!fileName.toLowerCase().endsWith(".apk")){
                        //获取文件的大小（单位/B[字节]）
                        long fileSize = part.getSize();
                        fileSize = fileSize/1204;//KB
                        long fileMax = FILE_MAX * 1024;
                        if(fileSize > fileMax){//文件超过限制
                            status = false;
                        }
                        break;
                    }
                }
            }
        }
        if(status){
            chain.doFilter(request,response);
        }else{
            response.getWriter().write(gson.toJson(ResultUtil.ERROR("文件超出限制")));
        }
    }

    @Override
    public void destroy() {
    }
}
